import { Button, Drawer, Form, Input } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import DrawerFooter from '@/components/DrawerFooter';

const SetPriceDrawer = (props) => {
  const { visible, onClose, onSubmit, task } = props;
  const [formData, setFormData] = useState({});
  const editCtx = useRef({ origin: {}, changed: {} }).current;

  useEffect(() => {
    const { carrierPrice, driverServiceFee, id: taskId } = task || {};
    const initData = {
      taskId,
      carrierPrice,
      driverServiceFee,
    };
    editCtx.origin = initData;
    setFormData(initData);
  }, [visible]);

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(formData, name, value);
    setFormData({ ...formData });

    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  return (
    <Drawer
      visible={visible}
      title={t`设置任务的佣金价格`}
      onClose={onClose}
      closeMode={['esc', 'mask', 'close']}
      width="40%"
    >
      <Form
        inline
        value={formData}
        onChange={handleChange}
      >
        <Form.Item
          label={t`公司费用`}
          required
          name="carrierPrice"
          requiredMessage="请输入公司费用"
        >
          <Input readOnly={global.isAdmin !== 'admin'} />
        </Form.Item>
        <br />
        <span style={{ margin: 10, color: '#6a6969' }}>{'(当前任务的实际价格可能与协议价格不同)'}</span>
        <br />
        <Form.Item
          label={t`司机费用`}
          required
          name="driverServiceFee"
          requiredMessage="请输入司机费用"
        >
          <Input />
        </Form.Item>
        <br />
        <span
          style={{
            margin: 10,
            color: '#6a6969',
          }}
        >{'(若本公司未开启“平台结算司机佣金”，则司机费用不可修改)'}
        </span>
      </Form>
      <DrawerFooter>
        <Form.Submit validate type="primary" onClick={() => onSubmit(formData)}>{t`保存`}</Form.Submit>
        <Button style={{ marginLeft: 8 }} onClick={onClose}>{t`取消`}</Button>
      </DrawerFooter>
    </Drawer>
  );
};

export default SetPriceDrawer;
